#!/bin/bash
# PCIe 设计完整测试套件
# 测试 moparse-rs 的所有功能

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 测试统计
TESTS_TOTAL=0
TESTS_PASSED=0
TESTS_FAILED=0

# 测试输出目录
TEST_OUTPUT_DIR="pcie_test_output"
rm -rf $TEST_OUTPUT_DIR
mkdir -p $TEST_OUTPUT_DIR

# 辅助函数
print_test() {
    echo -e "${YELLOW}[TEST $1]${NC} $2"
    TESTS_TOTAL=$((TESTS_TOTAL + 1))
}

pass_test() {
    echo -e "${GREEN}✓ PASS${NC}: $1"
    TESTS_PASSED=$((TESTS_PASSED + 1))
}

fail_test() {
    echo -e "${RED}✗ FAIL${NC}: $1"
    TESTS_FAILED=$((TESTS_FAILED + 1))
}

# 开始测试
echo "========================================"
echo "  PCIe 设计完整功能测试"
echo "========================================"
echo ""

# 测试 1: 解析文件列表
print_test "1" "解析 PCIe 文件列表"
if ../mo parse -f /home/apachee/trunk/Crystal/CrystalFlowAnalyzer/a9soc/design/pcie/src/DWC_pcie_dm.lst \
    -o $TEST_OUTPUT_DIR/pcie_dm.modb 2>&1 | tee $TEST_OUTPUT_DIR/test1.log; then
    
    # 检查文件是否生成
    if [ -f "$TEST_OUTPUT_DIR/pcie_dm.modb" ]; then
        file_size=$(stat -f%z "$TEST_OUTPUT_DIR/pcie_dm.modb" 2>/dev/null || stat -c%s "$TEST_OUTPUT_DIR/pcie_dm.modb")
        if [ $file_size -gt 0 ]; then
            pass_test "文件列表解析成功，生成 pcie_dm.modb ($file_size bytes)"
        else
            fail_test "生成的 modb 文件为空"
        fi
    else
        fail_test "未生成 modb 文件"
    fi
else
    fail_test "解析文件列表失败"
fi
echo ""

# 测试 2: 显示模块统计信息
print_test "2" "显示模块统计信息"
if ../mo show -i $TEST_OUTPUT_DIR/pcie_dm.modb 2>&1 | tee $TEST_OUTPUT_DIR/test2.log; then
    module_count=$(grep -c "Module name:" $TEST_OUTPUT_DIR/test2.log || echo "0")
    if [ $module_count -gt 0 ]; then
        pass_test "找到 $module_count 个模块"
    else
        fail_test "未找到任何模块"
    fi
else
    fail_test "显示模块信息失败"
fi
echo ""

# 测试 3: 显示顶层模块详细信息
print_test "3" "显示 DWC_pcie_dm 详细信息"
if ../mo show -i $TEST_OUTPUT_DIR/pcie_dm.modb -m DWC_pcie_dm -v 2>&1 | tee $TEST_OUTPUT_DIR/test3.log; then
    
    # 提取统计信息
    param_count=$(grep "Parameters (" $TEST_OUTPUT_DIR/test3.log | grep -oE '[0-9]+' | head -1)
    input_count=$(grep "Input ports:" $TEST_OUTPUT_DIR/test3.log | grep -oE 'Input ports: [0-9]+' | grep -oE '[0-9]+')
    output_count=$(grep "Output ports:" $TEST_OUTPUT_DIR/test3.log | grep -oE 'Output ports: [0-9]+' | grep -oE '[0-9]+')
    inst_count=$(grep "Instances (" $TEST_OUTPUT_DIR/test3.log | grep -oE '[0-9]+' | head -1)
    
    echo "  Parameters: $param_count"
    echo "  Input ports: $input_count"
    echo "  Output ports: $output_count"
    echo "  Instances: $inst_count"
    
    # 验证实例化解析是否工作
    if [ -n "$inst_count" ] && [ "$inst_count" -gt 0 ]; then
        pass_test "成功解析 $inst_count 个实例"
    else
        fail_test "实例化解析失败（Instance count = 0）"
    fi
else
    fail_test "显示详细信息失败"
fi
echo ""

# 测试 4: 层次结构显示（默认1层）
print_test "4" "显示模块层次结构（1层）"
if ../mo hierarchy -i $TEST_OUTPUT_DIR/pcie_dm.modb -m DWC_pcie_dm -l 1 2>&1 | tee $TEST_OUTPUT_DIR/test4.log; then
    if grep -q "Module Hierarchy:" $TEST_OUTPUT_DIR/test4.log; then
        pass_test "层次结构显示成功"
    else
        fail_test "层次结构显示格式错误"
    fi
else
    fail_test "层次结构显示失败"
fi
echo ""

# 测试 5: 层次结构显示（3层）
print_test "5" "显示模块层次结构（3层）"
if ../mo hierarchy -i $TEST_OUTPUT_DIR/pcie_dm.modb -m DWC_pcie_dm -l 3 2>&1 | tee $TEST_OUTPUT_DIR/test5.log; then
    pass_test "多层次结构显示成功"
else
    fail_test "多层次结构显示失败"
fi
echo ""

# 测试 6: CSV 导出
print_test "6" "导出层次结构到 CSV"
if ../mo hierarchy -i $TEST_OUTPUT_DIR/pcie_dm.modb -m DWC_pcie_dm -l 0 \
    -o $TEST_OUTPUT_DIR/hierarchy.csv 2>&1 | tee $TEST_OUTPUT_DIR/test6.log; then
    
    if [ -f "$TEST_OUTPUT_DIR/hierarchy.csv" ]; then
        line_count=$(wc -l < $TEST_OUTPUT_DIR/hierarchy.csv)
        pass_test "CSV 导出成功（$line_count 行）"
        
        # 显示前几行
        echo "  CSV 前 5 行："
        head -5 $TEST_OUTPUT_DIR/hierarchy.csv | sed 's/^/    /'
    else
        fail_test "CSV 文件未生成"
    fi
else
    fail_test "CSV 导出失败"
fi
echo ""

# 测试 7: 检查特定模块（pm_ctrl）
print_test "7" "检查 pm_ctrl 模块是否被正确识别"
if ../mo show -i $TEST_OUTPUT_DIR/pcie_dm.modb -m DWC_pcie_dm -v 2>&1 | grep -q "pm_ctrl u_pm_ctrl"; then
    pass_test "pm_ctrl 实例化正确识别（之前失败的跨行实例）"
else
    fail_test "pm_ctrl 未被识别"
fi
echo ""

# 测试 8: 检查其他关键模块
print_test "8" "检查其他关键模块实例化"
check_modules=("cx_pl u_cx_pl" "xadm u_xadm" "radm_dm u_radm_dm" "cdm u_cdm" "lbc u_lbc")
all_found=true

for mod in "${check_modules[@]}"; do
    if ../mo show -i $TEST_OUTPUT_DIR/pcie_dm.modb -m DWC_pcie_dm -v 2>&1 | grep -q "$mod"; then
        echo "  ✓ 找到: $mod"
    else
        echo "  ✗ 未找到: $mod"
        all_found=false
    fi
done

if $all_found; then
    pass_test "所有关键模块实例化都被正确识别"
else
    fail_test "部分模块实例化未被识别"
fi
echo ""

# 测试 9: 端口连接解析测试
print_test "9" "检查端口连接是否被解析"
if ../mo show -i $TEST_OUTPUT_DIR/pcie_dm.modb -m DWC_pcie_dm -v 2>&1 | grep -q "Port Connections"; then
    pass_test "端口连接信息已解析"
else
    echo "  ⚠ 注意: 端口连接信息未显示（可能未解析或未实例化端口）"
fi
echo ""

# 测试 10: 统计模块总数
print_test "10" "统计解析的模块总数"
total_modules=$(../mo show -i $TEST_OUTPUT_DIR/pcie_dm.modb 2>&1 | grep -c "Module name:" || echo "0")
if [ $total_modules -gt 200 ]; then
    pass_test "解析了 $total_modules 个模块（预期 ~290+）"
elif [ $total_modules -gt 100 ]; then
    echo "  ⚠ 警告: 只解析了 $total_modules 个模块，预期应该有更多"
    pass_test "部分模块已解析"
else
    fail_test "只解析了 $total_modules 个模块，严重不足"
fi
echo ""

# 测试总结
echo "========================================"
echo "  测试总结"
echo "========================================"
echo "总测试数: $TESTS_TOTAL"
echo -e "${GREEN}通过: $TESTS_PASSED${NC}"
echo -e "${RED}失败: $TESTS_FAILED${NC}"
echo ""

if [ $TESTS_FAILED -eq 0 ]; then
    echo -e "${GREEN}🎉 所有测试通过！${NC}"
    exit 0
else
    echo -e "${RED}❌ 有 $TESTS_FAILED 个测试失败${NC}"
    echo "详细日志请查看: $TEST_OUTPUT_DIR/"
    exit 1
fi
